package com.zhong.service;

import com.zhong.mapper.AccountMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author itsome on 2021-08-27 22:12:01
 */
@Slf4j
@Service
public class AccountServiceImpl {

    private static int index = 0;

    @Autowired
    private AccountMapper accountMapper;

    @GlobalTransactional
    public void debit(String userId, int money) {
        log.info("开始扣款");
        try {
            accountMapper.debit(userId, money);
        } catch (Exception e) {
            throw new RuntimeException("扣款失败，可能是余额不足！");
        }
        if (index++ % 2 == 0) {
            throw new RuntimeException("人为异常，index：" + index);
        }
        log.info("扣款成功");
    }

}
